package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BibliotecaApp {

    Library libraryObject;
    Menu menuObject;

    public BibliotecaApp()
    {
        //Initialisation of variables
        libraryObject =new Library();
        menuObject=new Menu(this);
    }

    public void displayMessageToConsole(String displayString)
    {
        System.out.println(displayString);
    }
    public String getWelcomeMessage()
    {
        //Displaying welcome message
        return "#\tWelcome to Bengalore Public Library\t#\n";
    }

    public int takeCustomerResponse(){
        int customerResponse;
        //Taking customer response
        InputStreamReader inputStreamReaderObject=new InputStreamReader(System.in);
        BufferedReader bufferedReaderObject=new BufferedReader(inputStreamReaderObject);
        try {
            customerResponse=Integer.parseInt(bufferedReaderObject.readLine());
        } catch (Exception e) {
            customerResponse=0;
        }
        return customerResponse;
    }

    public boolean menuOptionSelection(int customerResponse)
    {
        //Method returns false if customer wants to exit and true if customer has to revisit menu options
        if(customerResponse<=0||customerResponse>menuObject.menuItemArrayList.size())
        {
            System.out.print("\tSelect a valid option!!");
            return true;
        }

        //Taking action upon given customer response
        if(customerResponse==menuObject.menuItemArrayList.size())
            return false;
        else
        {
            MenuItem menuItemObject=menuObject.menuItemArrayList.get(customerResponse-1);
            menuItemObject.takeAction();
        }
        System.out.println("\n\n\tFor exit press 1 and any other key to go back to previous menu : ");
        if(takeCustomerResponse()==1)
            return false;
        else
            return true;
    }

    public static void main(String[] args)
    {
        BibliotecaApp bibliotecaAppObject=new BibliotecaApp();

        bibliotecaAppObject.displayMessageToConsole(bibliotecaAppObject.getWelcomeMessage());
        boolean loopExitCondition=true;
        int customerResponse=0;

        while (loopExitCondition)
        {
            bibliotecaAppObject.menuObject.displayMenuItems();
            customerResponse=bibliotecaAppObject.takeCustomerResponse();
            loopExitCondition=bibliotecaAppObject.menuOptionSelection(customerResponse);
        }
    }

}
